package cn.edu.hunan.pm.controller;
import cn.edu.hunan.pm.common.ParseBindingResult;
import cn.edu.hunan.pm.common.R;
import cn.edu.hunan.pm.exception.BusinessException;
import cn.edu.hunan.pm.pojo.User;
import cn.edu.hunan.pm.request.ReqUser;
import cn.edu.hunan.pm.service.UserService;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hb
 * @date 2024-06-19 10:31:46
 */
//@Controller
@RestController
public class UserManagerAction {

    //@Resource
    @Autowired
    private UserService userService;

    @PostMapping("/regist")
    public R regist(@RequestBody @Valid ReqUser user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String message= ParseBindingResult.parse(bindingResult);
            throw new BusinessException(100102,message);
        }
        User u=new User();
        u.setNickName(user.getNickName());
        u.setEmail(user.getEmail());
        u.setPwd(user.getPwd());
        userService.regist(u);

        return R.ok();
    }

    @GetMapping("/checkEmail")
    public R checkEmail(String email){

        userService.checkEmailExits(email);

        return R.ok().message("邮箱可以使用");

    }

    @PostMapping("/login")
   // @ResponseBody  //底层调用jackson以json的形式返回数据
    /**
     * @RequestBody 将请求参数中的json数据通过jackson封装成对象的对象
     */
    public R login(@RequestBody @Valid ReqUser user, HttpSession session, BindingResult bindingResult){

       if(bindingResult.hasErrors()){
           String message= ParseBindingResult.parse(bindingResult);
           throw new BusinessException(100102,message);
       }


        //  R.ok().data("email",user.getEmail());
        User u = userService.login(user.getEmail(), user.getPwd());
       //将用户信息存入到session中
        session.setAttribute("user",u);
        return R.ok().data("user",u).data("sessionid",session.getId()) ;
    }
}
